const express = require('express')
const cors = require('cors')
const app = express()
const port = 3000
app.use(cors()) // cors跨域

var mysql = require('mysql'); // mysql
var bcrypt = require('bcryptjs');
var db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123123',
    database: 'kw37'
});

// 引入 token
var jwt = require('jsonwebtoken');
let secret = "mini"

// 解析json
app.use(express.json())



// getkb
app.get('/getkb', (req, res) => {
  // mysql 查询数据
  db.query(`SELECT count(*) AS num FROM kblist `,(error, result) => {
    if (error) throw error;
    res.send({code:0,total:result[0].num})
  });
})

// kblist
app.get('/kblist', (req, res) => {
  // mysql 查询数据,并倒序
  let curr = Number(req.query.curr) - 1
  let limit = Number(req.query.limit);
  db.query(`SELECT * FROM kblist ORDER BY id DESC limit ?,?`, [curr*limit,limit],(error, result) => {
    if (error) throw error;
    res.send({code:0,result})
  });
})
// kbdel
app.post('/kbdel', (req, res) => {
  // mysql 删除数据（id）
  let {id} = req.body
  db.query(`DELETE FROM kblist WHERE id=?`,[id], (error, result) => {
    if (error) throw error;
    res.send({code:0,msg:"删除成功"})
  });
})
// kbone
app.post('/kbone', (req, res) => {
  // mysql 查询一个数据（id）
  let {id} = req.body.row
  db.query(`SELECT * FROM kblist WHERE id=?`,[id], (error, result) => {
    if (error) throw error;
    res.send({result})
  });
})
// kbedit
app.post('/kbedit', (req, res) => {
  // mysql 更新一个数据（id）
  let {id,time,name,tel,origin,beizhu} = req.body
  db.query(`UPDATE kblist SET time=?,name=?,tel=?,origin=?,beizhu=? WHERE id=?`,[new Date(time),name,tel,origin,beizhu,id], (error, result) => {
    if (error) throw error;
    res.send({code:0,msg:"保存成功"})
  });
})

// kbadd
app.post('/kbadd', (req, res) => {
  // mysql 插入数据
  let {time,name,tel,origin,beizhu} = req.body
  if (name === ''|| tel === '' || time === '') {
    res.send({code:1,msg:"添加失败"})
  } else {
      db.query(`INSERT INTO kblist (time,name,tel,origin,beizhu) VALUES (?,?,?,?,?)`,[new Date(time),name,tel,origin,beizhu], (error, result) => {
        if (error) throw error;
            res.send({code:0,msg:"添加成功"})
      });
  }
})







// 获取前端发过来的 token 并验证
app.post('/verifyToken',(req,res) => {
    // console.log(req.headers.token);
    try {
        // 解析 token
        var decoded = jwt.verify(req.headers.token, secret);
        //如果正确 返回 token 组成的对象,否则会抛出错误 => JsonWebTokenError: invalid signature
        res.send({code:0,msg:'token有效'})
      } catch(err) {
        // err
        res.send({code:1,msg:'token过期或有误,请重新登录'})
      }
})




// register --- post请求
app.post('/register', (req, res) => {
    let { username, password } = req.body
    console.log(req.body);
    if (username.trim() === "") {
        res.send({ code: 2, msg: '用户名不能为空' })
        return
    }
    // mysql 查询数据
    db.query(`SELECT username FROM user WHERE username=?`, [username], (error, result) => {
        if (error) throw error;
        if (result[0]) {
            res.send({ code: 1, msg: '用户名已经存在' })
        } else {
            // 插入数据前  加密密码
            var bpassword = bcrypt.hashSync(password, 8);
            db.query(`INSERT INTO user (username,password) VALUES (?,?)`, [username, bpassword], (error, result) => {
                if (error) throw error;
                res.send({ code: 0, msg: '注册成功' })
            })
        }
    });
})




// login --- post请求
app.post('/login', (req, res) => {
    // console.log(req.body);
    let { username, password } = req.body
    // mysql 查询数据
    db.query(`SELECT id,username,password FROM user WHERE username=?`,[username], function (error, result) {
        if (error) throw error;
        // console.log(result[0]); 
        // 如果用户名不存在会返回 undefined => false  存在的话 返回一个对象 {} => true 
        // 加载hash密码
        // console.log(bcrypt.compareSync(password, result[0].password));
        
        // 如果不存在就会返回错误
        if (result[0]) {
            if (bcrypt.compareSync(password, result[0].password)) {
                // 并设置 token 令牌  -- 传入一个对象和密钥
                // id和username组成的令牌
                var token = jwt.sign({id:result[0].id,username:result[0].username}, secret,{ expiresIn: '1d' });  
                // console.log(token);
                
                res.send({ code: 0, msg: '登录成功', token, username:result[0].username});
            } else {
                res.send({ code: 1, msg: '用户名或密码错误！' })
            }
        } else {
            res.send({ code: 1, msg: '用户名或密码错误！' })
        }
    });

})



// 监听
app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})
